

#include <stdio.h> 
#include <avr/io.h>
#include <util/delay.h>
#include <avr/interrupt.h>

// Declarations

void PulseSonar(void);
ISR(SIG_INPUT_CAPTURE1);
extern uint16_t volatile SonarReturnTime;// 'Extern' Lets you access variable in the ___.c file, if declared there
extern uint8_t volatile InPulse;			// State machine variable

// Primary function

void PulseSonar() {
	TCCR1B|=_BV(CS12);						// Prescalar is clock/256 (16 us per count)
	cli();									// Clears interrupts temporarily
	TIMSK&=~_BV(TICIE1); 					// Disable input capture pin interrupt (ICP)

	DDRD |=0x40;							// Change D6 (7th pin) to output mode
	PORTD |=0x40;							// Turn on D6
	_delay_us(5);							// Enable Port D as input for 5us
	PORTD &=~0x40;							// Turn off D6
	DDRD &=~0x40;							// Change D6 to input mode

	//Re-enable ICP (PD6 as input)
	TIMSK|=_BV(TICIE1); 					// Renable ICP
	TCCR1B |=_BV(ICES1); 					// Responds to rising edge initially
	InPulse=1;								// Variable for state machine
	sei();
}

ISR(SIG_INPUT_CAPTURE1) {
	if(InPulse==1) {						// First state of machine (captured rising edge, start of pulse in)
		TCNT1 = 0;							// Start counting
		TCCR1B &= ~_BV(ICES1); 				// Sets capture pin to respond to falling edge
		InPulse = 2;
	}
	else if(InPulse==2) {					// Next state of machine (captured falling edge, end of pulse in)
		SonarReturnTime = ICR1;				// Reads from ICR1, which was equal to TCNT1 when interrupt is thrown
		InPulse = 0;
	}
}
